package com.gxuwz.stats.controller;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.code.kaptcha.Producer;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

//    @Autowired
//    private ISysConfigService configService;

    @GetMapping("/captchaImage")
    public Map<String, Object> getCode(HttpServletRequest request) throws IOException {
        Map<String, Object> ajax = new HashMap<>();
        boolean captchaEnabled = true; // 你可以根据需要决定是否启用验证码
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 生成 uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = "math"; // 或 "char"，可根据需要切换
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        // 存到 Session（uuid -> code）
        HttpSession session = request.getSession();
        Map<String, String> captchaMap = (Map<String, String>) session.getAttribute("captchaMap");
        if (captchaMap == null) {
            captchaMap = new HashMap<>();
        }
        captchaMap.put(uuid, code);
        session.setAttribute("captchaMap", captchaMap);

        // 转为 base64
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        String imgBase64 = Base64.getEncoder().encodeToString(os.toByteArray());

        ajax.put("uuid", uuid);
        ajax.put("img", imgBase64);
        return ajax;
    }
}
